<?php
/**
 * Created by PhpStorm.
 * User: Fedax
 * Date: 2018/7/15
 * Time: 18:15
 */

namespace app\admin\model;

use think\model\concern\SoftDelete;
use app\admin\model\DailyLog;

class Admin extends ManageBase
{
    use SoftDelete;
    protected $createTime = 'add_time';
    protected $deleteTime = 'delete_time';
    protected $autoWriteTimestamp = true;
    /**
     * @param $username
     * @param $password
     * @return array
     * @property  string $user_token
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function loginByUserNameAndPassword($username, $password)
    {
        $modelReturnData=array();
        $data = $this->where('admin_name',$username)->find();
        if ($data['admin_password'] != md5(trim($password))) {
            $modelReturnData['ret']=400;
            $modelReturnData['msg']='密码错误';
            return $modelReturnData;
        }
        //$data->user_token = set_token();
        $data->user_token = md5(uniqid(md5(microtime(true)),true));
        $data->expire_time=time() + 604800;
        if ($data->save()) {
            session('admin_token', $data->user_token);
            session('admin_id', $data['id']);
            session('role_id', $data['role_id']);
            session('admin_name',$username);
            $modelReturnData['ret'] = 200;
            DailyLog::create(['admin_id'=>$data['id'],'content'=>'登录成功','type'=>1,'create_time'=>date('Y-m-d H:i:s')]);
            return $modelReturnData;
        }
        return redirect('/Miss');

    }

    /**
     * @param $token
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function checkToken($token){
        $modelReturnData=array();
        $data = $this->where('user_token',$token)->find();
        if (!empty($data)) {
            if (time() - $data['expire_time'] > 0) {
                $modelReturnData['ret']=400;
                $modelReturnData['msg']='账号过期';
                return $modelReturnData;
            }
            $data->expire_time=time() + 604800;
            $data->save();
            $modelReturnData['ret']=200;
            $modelReturnData['data'] = $data;
            return $modelReturnData;
        }
        $modelReturnData['ret']=400;
        $modelReturnData['msg']='账号非法';
        return $modelReturnData;
    }

    /**
     * @param $page_config
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getDataList($page_config)
    {
        return $this
            ->where('id', '<>', '1')
            ->field('id,admin_name,admin_password,role_id')
            ->order('id desc')
            ->paginate($page_config);
    }
}